#!/bin/bash

set -x

panic()
{
	echo "$@"
	exit
}

# Default PATH differs between shells, and is not automatically exported
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
haveged >/dev/null 2>&1 &

[ -f /etc/ssh/ssh_host_rsa_key ] || /usr/bin/ssh-keygen -t rsa -P "" -f /etc/ssh/ssh_host_rsa_key
[ -f /etc/ssh/ssh_host_ecdsa_key ] || /usr/bin/ssh-keygen -t rsa -P "" -f /etc/ssh/ssh_host_ecdsa_key
[ -f /etc/ssh/ssh_host_ed25519_key ] ||  /usr/bin/ssh-keygen -t rsa -P "" -f /etc/ssh/ssh_host_ed25519_key
mkdir -p /var/run/sshd
/usr/sbin/sshd -D >/dev/null 2>&1 &
/usr/sbin/licensed >/dev/null 2>&1 &

[ -f /root/.vimrc ] || cp /etc/vim/vimrc /root/.vimrc
hostname $(cat /etc/hostname)

APP=

echo $@

ifconfig lo 127.0.0.1/8

data_path=$1

if mountpoint -q  ${data_path};then
	echo "Data: " ${data_path}
else
	echo "The data partition is not mounted"
	/bin/bash
	exit
fi

TTY=
APP=

# Parse command line options
for x in $(cat /proc/cmdline); do
	case $x in
	app=*)
		APP=${x#app=}
		;;
	console=*)
		TTY=${x#console=}
		;;
esac
done

if [ -x ${data_path}/autostart ]; then
	APP=${data_path}/autostart
fi

if [ -z "${APP}" ]; then
	echo "Application not specified. Boot arguments must include a app=/app_path/app parameter or Add launcher in /data/autostart"
elif [ -x ${data_path}/${APP} ]; then
	exec ${data_path}/${APP} &
else
	echo "The permission is incorrect or the file is not found: " ${APP}
fi

export TERM=linux
if [ -z "${TTY}" ]; then
	echo "Console not specified. Boot arguments must include a console parameter"
	/bin/bash
else
	port=$(echo "${TTY}" | awk -F ',' '{printf $1}')
	band=$(echo "${TTY}" | awk -F ',' '{printf $2}')
	if [ ! -z "$band" ]; then
		band=${band%%[a-z|A-Z]*}
	fi
	echo ${port}
	echo ${band}
	while [ 1 ];
	do
		setsid getty -a root ${port} ${band}
	done
fi
